import React, { useState } from "react";
import { View, Text, TouchableOpacity, Alert } from "react-native";
import { useTheme } from "@/contexts/ThemeContext";
import { Ionicons } from "@expo/vector-icons";
import { createStyles } from "./index.style";
import { Divider } from "@rneui/themed";
import InputModal from "./InputModal";
import QRCodeModal from "@/components/Global/QRCodeModal";

// 群聊头像的mock数据
const MOCK_GROUP_AVATARS = [
  "https://randomuser.me/api/portraits/men/32.jpg",
  "https://randomuser.me/api/portraits/women/44.jpg",
  "https://randomuser.me/api/portraits/men/86.jpg",
  "https://randomuser.me/api/portraits/women/63.jpg",
  "https://randomuser.me/api/portraits/men/57.jpg",
];

interface GroupInfoItemProps {
  title: string;
  content: string;
  showArrow?: boolean;
  onPress?: () => void;
}

const GroupInfoItem = ({
  title,
  content,
  showArrow = true,
  onPress,
}: GroupInfoItemProps) => {
  const { colors } = useTheme();
  const styles = createStyles(colors);

  return (
    <>
      <TouchableOpacity
        style={styles.itemContainer}
        onPress={onPress}
        disabled={!onPress}
      >
        <View style={styles.leftContainer}>
          <Text style={styles.itemTitle}>{title}</Text>
          <Text style={styles.itemContent} numberOfLines={1}>
            {content}
          </Text>
        </View>
        {showArrow && (
          <View style={styles.rightContainer}>
            <Ionicons
              name="chevron-forward"
              size={20}
              color={colors.text.secondary}
              style={styles.chevron}
            />
          </View>
        )}
      </TouchableOpacity>
      <Divider style={{ backgroundColor: "#E1E8ED" }} />
    </>
  );
};

const GroupInformation = () => {
  const { colors } = useTheme();
  const styles = createStyles(colors);

  // 从mock数据中随机选择一个头像
  const randomAvatar =
    MOCK_GROUP_AVATARS[Math.floor(Math.random() * MOCK_GROUP_AVATARS.length)];

  // 模拟数据
  const [groupInfo, setGroupInfo] = useState({
    groupName: "鸽王精英",
    groupId: "701519925",
    groupAnnouncement: "王者荣耀开黑交友兴趣群，来了就是朋友，一起开黑！",
    myNickname: "小兵",
    groupRemark: "",
    groupAvatar: randomAvatar, // 使用随机选择的mock头像
  });

  // Modal状态
  const [modalConfig, setModalConfig] = useState<{
    visible: boolean;
    type: "groupName" | "announcement" | "myNickname" | "groupRemark" | null;
    title: string;
    initialValue: string;
    placeholder: string;
    hint: string;
    multiline: boolean;
    maxLength?: number;
    validator?: (value: string) => boolean;
    errorMessage?: string;
  }>({
    visible: false,
    type: null,
    title: "",
    initialValue: "",
    placeholder: "",
    hint: "",
    multiline: false,
  });

  // QRCode Modal状态
  const [qrCodeModalVisible, setQRCodeModalVisible] = useState(false);

  const openModal = (type: typeof modalConfig.type) => {
    let config = {
      visible: true,
      type,
      title: "",
      initialValue: "",
      placeholder: "",
      hint: "",
      multiline: false,
      maxLength: undefined,
      validator: undefined,
      errorMessage: undefined,
    };

    switch (type) {
      case "groupName":
        config.title = "群聊名称";
        config.initialValue = groupInfo.groupName;
        config.placeholder = "请输入群聊名称";
        config.hint = "群聊名称将显示在会话列表和群聊设置中";
        config.multiline = false;
        config.maxLength = 20;
        config.validator = (value) => value.length >= 1 && value.length <= 20;
        config.errorMessage = "群聊名称长度为1-20个字符";
        break;
      case "announcement":
        config.title = "群公告";
        config.initialValue = groupInfo.groupAnnouncement;
        config.placeholder = "请输入群公告";
        config.hint = "群公告将在群聊信息页面展示";
        config.multiline = true;
        config.maxLength = 200;
        config.validator = (value) => value.length <= 200;
        config.errorMessage = "群公告最多200个字符";
        break;
      case "myNickname":
        config.title = "我的群昵称";
        config.initialValue = groupInfo.myNickname;
        config.placeholder = "请输入在本群中的昵称";
        config.hint = "群昵称仅在本群中显示，不会影响您的个人资料";
        config.multiline = false;
        config.maxLength = 20;
        config.validator = (value) => value.length <= 20;
        config.errorMessage = "群昵称最多20个字符";
        break;
      case "groupRemark":
        config.title = "群聊备注";
        config.initialValue = groupInfo.groupRemark;
        config.placeholder = "请输入群聊备注";
        config.hint = "群聊备注仅自己可见";
        config.multiline = false;
        config.maxLength = 30;
        config.validator = (value) => value.length <= 30;
        config.errorMessage = "群聊备注最多30个字符";
        break;
    }

    setModalConfig(config);
  };

  const closeModal = () => {
    setModalConfig((prev) => ({ ...prev, visible: false }));
  };

  const handleSave = (value: string) => {
    // 根据类型更新对应的群聊信息
    switch (modalConfig.type) {
      case "groupName":
        setGroupInfo((prev) => ({ ...prev, groupName: value }));
        console.log("群聊名称已更新:", value);
        // 这里可以添加API调用，更新服务器端数据
        break;
      case "announcement":
        setGroupInfo((prev) => ({ ...prev, groupAnnouncement: value }));
        console.log("群公告已更新:", value);
        break;
      case "myNickname":
        setGroupInfo((prev) => ({ ...prev, myNickname: value }));
        console.log("我的群昵称已更新:", value);
        break;
      case "groupRemark":
        setGroupInfo((prev) => ({ ...prev, groupRemark: value }));
        console.log("群聊备注已更新:", value);
        break;
    }
  };

  const handleGroupNamePress = () => {
    openModal("groupName");
  };

  const handleGroupIdPress = () => {
    // 显示群聊二维码
    setQRCodeModalVisible(true);
  };

  const handleAnnouncementPress = () => {
    openModal("announcement");
  };

  const handleMyNicknamePress = () => {
    openModal("myNickname");
  };

  const handleGroupRemarkPress = () => {
    openModal("groupRemark");
  };

  const handleShareQRCode = () => {
    // 分享群聊二维码的逻辑
    Alert.alert("分享", "群聊二维码已生成，请选择分享方式");
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>群聊信息</Text>
      </View>

      <GroupInfoItem
        title="群聊名称"
        content={groupInfo.groupName}
        onPress={handleGroupNamePress}
      />

      <GroupInfoItem
        title="群号和二维码"
        content={groupInfo.groupId}
        onPress={handleGroupIdPress}
      />

      <GroupInfoItem
        title="群公告"
        content={groupInfo.groupAnnouncement || "暂无公告"}
        onPress={handleAnnouncementPress}
      />

      <GroupInfoItem
        title="我的群昵称"
        content={groupInfo.myNickname || "未设置"}
        onPress={handleMyNicknamePress}
      />

      <GroupInfoItem
        title="群聊备注"
        content={groupInfo.groupRemark || "未设置"}
        onPress={handleGroupRemarkPress}
      />

      {/* 输入模态框 */}
      <InputModal
        visible={modalConfig.visible}
        onClose={closeModal}
        title={modalConfig.title}
        initialValue={modalConfig.initialValue}
        placeholder={modalConfig.placeholder}
        hint={modalConfig.hint}
        multiline={modalConfig.multiline}
        maxLength={modalConfig.maxLength}
        validator={modalConfig.validator}
        errorMessage={modalConfig.errorMessage}
        onSave={handleSave}
      />

      {/* 二维码模态框 */}
      <QRCodeModal
        visible={qrCodeModalVisible}
        onClose={() => setQRCodeModalVisible(false)}
        groupId={groupInfo.groupId}
        groupName={groupInfo.groupName}
        avatar={groupInfo.groupAvatar}
        onShare={handleShareQRCode}
        id={groupInfo.groupId}
        name={groupInfo.groupName}
        type="group"
      />
    </View>
  );
};

export default GroupInformation;
